package com.cashmate.struts;

import com.cashmate.hibernate.dao.DocumentDAO;
import com.cashmate.hibernate.dao.LoansDAO;
import com.cashmate.hibernate.dao.LoanverificationDAO;
import com.cashmate.hibernate.dao.RatesDAO;
import com.cashmate.hibernate.dao.VoucherDAO;
import com.cashmate.hibernate.dao.VoucherRatesDAO;
import com.cashmate.hibernate.pojo.Documents;
import com.cashmate.hibernate.pojo.Employees;
import com.cashmate.hibernate.pojo.Loans;
import com.cashmate.hibernate.pojo.Loanverification;
import com.cashmate.hibernate.pojo.Rates;
import com.cashmate.hibernate.pojo.Voucher;
import com.cashmate.hibernate.pojo.VoucherRates;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Result;


import com.opensymphony.xwork2.ActionSupport;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.struts2.ServletActionContext;
import org.hibernate.Criteria;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

public class Approval_SaveLoan extends ActionSupport{
  private LoanverificationDAO loanverdao = (LoanverificationDAO) ServletActionContext.getServletContext().getAttribute("loanverificationDAO");
  private VoucherDAO voucherDAO = (VoucherDAO) ServletActionContext.getServletContext().getAttribute("voucherDAO");
  private VoucherRatesDAO vrDAO = (VoucherRatesDAO) ServletActionContext.getServletContext().getAttribute("voucherRatesDAO");
  private RatesDAO rateDAO = (RatesDAO) ServletActionContext.getServletContext().getAttribute("ratesDAO");
  private DocumentDAO documentDAO = (DocumentDAO) ServletActionContext.getServletContext().getAttribute("documentDAO");
  private LoansDAO loanDAO = (LoansDAO) ServletActionContext.getServletContext().getAttribute("loansDAO");
  private String selected;
  private String loc;

  @Actions( {
    @Action(value = "/saveloan", results = {
      @Result(location = "${loc}", name = "success", type = "redirect"), @Result(location = "${loc}", name = "input")
    })
  })

  @Override
  public String execute() throws Exception{
      SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
      Employees emp = (Employees) ServletActionContext.getRequest().getSession().getAttribute("employee");
      String mask = "00000";
      DecimalFormat df = new DecimalFormat(mask);
      String mask2 = "00";
      DecimalFormat df2 = new DecimalFormat(mask2);
      loc = "/loanapproval.jsp?cat=request";
      List<Loanverification> loanverifications = new ArrayList<Loanverification>();
      String[] sel = selected.split(",");
      for(String s : sel){
        try{
            int id = Integer.parseInt(s);
            loanverifications.add(loanverdao.get(id));
        }catch (Exception e){
            return ERROR;
        }
      }
      try{
      for(Loanverification l : loanverifications){
          l.setStatus("Approved");
          loanverdao.update(l);
          
          Voucher voucher = new Voucher();
          voucher.setDate(formatter.format(new Date()));
          voucher.setEmployeesByPreparedby(emp);
          voucherDAO.insert(voucher);
         
          Documents voucherD = new Documents();
          voucherD.setDocumentdate(formatter.format(new Date()));
          voucherD.setDocumentno("V" + l.getBorrowers().getBranches().getBranchcode() + df.format(voucher.getVoucherid()));
          voucherD.setDocumenttype("Voucher");
          voucherD.setIsactive(true);
          documentDAO.insert(voucherD);
          
          voucher.setDocuments(voucherD);
          voucherDAO.update(voucher);
          
          double loanable = l.getAmountrequested();
          double suggested = (double) l.getAmountrequested();
          
          DetachedCriteria criteria = criteria = DetachedCriteria.forClass(Rates.class);
          criteria.createCriteria("products", "p").setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);          
          criteria.add(Restrictions.eq("p.productid", l.getProducts().getProductid()));
          int sizeofrate = rateDAO.countByCriteria(criteria);
          criteria.setProjection(null);
          criteria.setResultTransformer(Criteria.ROOT_ENTITY);

          
          List<Rates> rates = rateDAO.findByCriteria(criteria, 0, sizeofrate);
          
          for(Rates r : rates){
              double amount = 0;
                      
              if(r.getRatename().equalsIgnoreCase("Documentation and Notarial Fee") && r.getProducts().getProductname() == 100){
                  amount = 10;
              }
              
              amount = amount + (suggested * r.getRate());              
              VoucherRates vr = new VoucherRates();
              vr.setAmount(amount);
              vr.setRates(r);
              vr.setVoucher(voucher);
              vrDAO.insert(vr);
              
              loanable = loanable - amount;
          }    
          
         
          Loans loan = new Loans();
          loan.setDateapproved(formatter.format(new Date()));
          loan.setLoanamount(suggested);
          loan.setNetloanableamount(loanable);
          loan.setAmortizationperday(loanable / l.getProducts().getProductname());
          loan.setOverdue(0);
          loan.setBalance(loanable);
          loan.setTerm(l.getProducts().getProductname());
          loan.setVoucherprint(false);
          loan.setCheckprint(false);
          loan.setAcknowledgementprint(false);
          loan.setStatus("Pending");
          loan.setBorrowers(l.getBorrowers());
          loan.setLoanverification(l);
          loan.setAreas(l.getBorrowers().getAreas());
          loan.setDaysleft(l.getProducts().getProductname());
          
          int loanNo = 1;
          if(l.getBorrowers().getFirstlast() != null){
              if(l.getBorrowers().getSecondlast() != null){
                  loanNo = l.getBorrowers().getSecondlast().getLoanno() + 1;
              }else{
                  loanNo = l.getBorrowers().getFirstlast().getLoanno() + 1;
              }
          }
          
          loan.setLoanno(loanNo);
          loanDAO.insert(loan);
          
          Documents loanD = new Documents();
          loanD.setDocumentno(l.getBorrowers().getBranches().getBranchcode() + df.format(loan.getLoanid()) + df2.format(loan.getLoanno()));
          loanD.setDocumentdate(formatter.format(new Date()));
          loanD.setDocumenttype("Promissory Note");
          loanD.setIsactive(true);
          documentDAO.insert(loanD);
          
          loan.setDocuments(loanD);
          loanDAO.update(loan);
          
          voucher.setLoans(loan);
          voucherDAO.update(voucher);
          
      }}
      catch (Exception e){
          e.printStackTrace();
      }
      return SUCCESS;
  }

    public void setSelected(String selected) {
        this.selected = selected;
    }
    
    public String getLoc() {
        return loc;
    }

}
